package com.archgeek.rpc.pekko;

import com.typesafe.config.ConfigFactory;
import org.apache.pekko.actor.AbstractActor;
import org.apache.pekko.actor.ActorRef;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.actor.Props;
import org.apache.pekko.japi.pf.ReceiveBuilder;
import org.apache.pekko.pattern.Patterns;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeoutException;

/**
 * @author pizhihui
 * @date 2024-05-23 06:49
 */
public class PekkoLocalDemo {


    public static void main(String[] args) throws InterruptedException, TimeoutException {


//        ConfigFactory.load()

        ActorSystem actorSystem = ActorSystem.create("actor-system");
        ActorRef actorRef = actorSystem.actorOf(Props.create(MyActor.class), "my-actor");

        // 非阻塞
        actorRef.tell(new Start(),  ActorRef.noSender());

        // 阻塞,等待回应消息
        Future<Object> ask = Patterns.ask(actorRef, new ProcessData(), 1000);
        Object result = Await.result(ask, Duration.create("1s"));
        System.out.println("拿到结果: " + result);
        System.out.println("主程序启动....");

    }
}
class MyActor extends AbstractActor {
    @Override
    public Receive createReceive() {
        return ReceiveBuilder.create()
                .match(Start.class, this::handleStart)
                .match(ProcessData.class, this::handleProcessData)
                .build();
    }

    private void handleStart(Start start) {
        System.out.println("处理start 事件");
    }

    private void handleProcessData(ProcessData processData) {
        System.out.println("处理数据事件");
        ActorRef sender = getSender();
        sender.tell("返回消息了", getSelf());
    }

}
// 消息体
class Start {

}
class ProcessData {

}